import javax.swing.*;
import java.awt.*;

public class CustomDesktopTimer {
    private static Timer timer;
    private static int counter;

    public static void main(String[] args) {
        JFrame frame = new JFrame("自定义桌面定时器");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(350, 200);
        frame.setLocationRelativeTo(null);

        // 输入时间
        JTextField inputField = new JTextField(10);
        JLabel inputLabel = new JLabel("请输入时间（秒）：");
        JButton startButton = new JButton("开始计时");

        // 倒计时显示
        JLabel countdownLabel = new JLabel("等待输入时间...", SwingConstants.CENTER);
        countdownLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));

        // 布局
        JPanel panel = new JPanel();
        panel.add(inputLabel);
        panel.add(inputField);
        panel.add(startButton);

        frame.add(panel, BorderLayout.NORTH);
        frame.add(countdownLabel, BorderLayout.CENTER);

        // 按钮事件
        startButton.addActionListener(e -> {
            try {
                int seconds = Integer.parseInt(inputField.getText().trim());
                if (seconds <= 0) {
                    JOptionPane.showMessageDialog(frame, "请输入大于 0 的数字！");
                    return;
                }

                // 停掉之前的 timer
                if (timer != null && timer.isRunning()) {
                    timer.stop();
                }

                counter = seconds;
                countdownLabel.setText("剩余时间: " + counter + " 秒");

                // 创建定时器，每秒更新一次
                timer = new Timer(1000, evt -> {
                    counter--;
                    if (counter >= 0) {
                        countdownLabel.setText("剩余时间: " + counter + " 秒");
                    } else {
                        timer.stop();
                        JOptionPane.showMessageDialog(frame, "时间到啦！");
                    }
                });
                timer.start();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(frame, "请输入合法的数字！");
            }
        });

        frame.setVisible(true);
    }
}
